#include <iostream>
#include <vector>
#include <pthread.h>
#include <string>
#include <unistd.h>

pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

int cnt = 1000;

void *threadrun(void *args)
{
    std::string name = (char*)args;
    while(1)
    {
        pthread_mutex_lock(&glock);
        // 让对应线程等待
        pthread_cond_wait(&gcond, &glock);
        std::cout << name << " 计算: " << cnt << std::endl;
        cnt++;
        pthread_mutex_unlock(&glock);
    }
    return 0;
}

int main()
{
    std::vector<pthread_t> threads;
    for(int i = 0; i < 5; i++)
    {
        pthread_t tid;
        char *name = new char[64];
        snprintf(name, 64, "thread_%d", i+1);
        int n = pthread_create(&tid, nullptr, threadrun, name);
        if(n != 0) continue;;
        threads.push_back(tid);
        sleep(1);
    }

    sleep(5);
    while(1)
    {
        //pthread_cond_broadcast(&gcond);
        pthread_cond_signal(&gcond);
        sleep(1);
    }

    for(auto &tid : threads)
    {
        pthread_join(tid, nullptr);
    }

    return 0;
}